#ifndef mW_lua_include
#define mW_lua_include

#include <lua5.1/lua.h>
#include <lua5.1/lauxlib.h>
#include <lua5.1/lualib.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include "error.h"
#include "list.h"


#define DEBUG_LUA 0


#define mW_LUA_TYPE_INVALID 0
#define mW_LUA_TYPE_INTEGER 1
#define mW_LUA_TYPE_STRING  2
#define mW_LUA_TYPE_TABLE   3


typedef struct
{
	unsigned char key_type;
	unsigned char data_type;
	void * key;
	void * data;
} mW_lua_variable;



/*
 * Allocates memory for a string at position idx on the lua stack, copies
 *   the lua string into the newly allocate memory, and returns a pointer
 *   to the string
 */
char * mW_lua_copy_string_from_stack (lua_State * l_vm, int idx);


/*
 * Just a wrapper around luaL_newstate()
 */
lua_State * mW_lua_create ();


/*
 * Just a wrapper around lua_close()
 */
void mW_lua_destroy (lua_State * l_vm);


/*
 * Converts a lua_Integer to int.
 */
int mW_lua_integer_to_int (lua_Integer integer);


/*
 * Performs a protected call no the lua stack, handling any errors.
 * Returns 1 on success
 * Returns 0 on failure (Such as lua_pcall returns an error)
 */
int mW_lua_p_call (lua_State * l_vm, int nargs, int nresults);


/*
 * This creates a mW_lua_variable of type table.
 * mW_lua_variables of type data have a mW_list as their data.
 * Returns a pointer to a mW_lua_variable on success
 * Returns Null on failure
 */
mW_lua_variable * mW_lua_get_table (lua_State * l_vm);


/*
 * Loads the lua file filename and runs it with the lua state l_vm.
 * Returns 1 on success
 * Returns 0 on any errors
 */
int mW_lua_run_file (lua_State * l_vm, const char * filename);


/*
 * Handles lua errors.
 */
void mW_lua_script_error (char * text);


/* 
 * Destroys/frees the memory for variable
 */
void mW_lua_variable_destroy (mW_lua_variable * variable);


/*
 * Cleans a variable, freeing all memory pointed to by the variable, but
 *   not freeing the variable itself. This is useful for destroying lists
 *   of variables (read tables)
 */
void mW_lua_variable_clean (mW_lua_variable * variable);

#endif // mW_lua_include
